layui.use(['form','tree','element','table','laytpl','treeGrid','layer','jquery'],function(){
    var form = layui.form,
        element = layui.element;
    $ = layui.$;
    var layer = parent.layer === undefined ? layui.layer : top.layer;
    var table = layui.table;
    var laytpl = layui.laytpl;
    var layedit = layui.layedit;

    //场景数据
    var height = $(document).height();
    $(".orgbox").css('height',(height - 40) + "px");
    $(window).on("resize",function () {
        $(".orgbox").css('height',(height - 40) + "px");
    });
    var treeData = {
        elem: '#tree' //指定元素
        , target: '_blank' //是否新选项卡打开（比如节点返回href才有效）
        , click: function (item) { //点击节点回调
            //刷新右侧设备列表和检测项目列表
            $.get("/equipment/query?sceneId=" + item.id,function (data) {
                $("#equipment-list").html('');
                $("#equipment-list").append('<option value="">请选择</option>');
                $.each(data.data,function (i,ele) {
                    $("#equipment-list").append('<option value="'+ ele.id +'">'+ ele.name +'</option>');
                });
                form.render('select');
            });
        },
        nodes:null
    };
    //异步加载设备所处场景数据
    $.get('/scene/tree',function(data) {
        if (data.data.length != 0) {
            data.data[0].spread = true;
        }
        treeData.nodes = data.data;
        layui.tree(treeData);
    });

    //默认加载所有的采集设备列表
    $.get("/equipment/list",function (data) {
        /*$("#equipment-list").append('<option value="">请选择</option>');*/
        $.each(data.data,function (i,ele) {
            $("#equipment-list").append('<option value="'+ ele.id +'">'+ ele.name +'</option>');
        });
        form.render('select');
        //刷新设备对应的数据采集项
        // form.on('select(equipment-list)',function (data) {
        //     $.get("/equipment/channel/query?equipmentId=" + data.value,function (data) {
        //         $("#checkItem").html("");
        //         $("#checkItem").append('<option value="">请选择</option>');
        //         $.each(data.data,function (i,ele) {
        //             $("#checkItem").append('<option value="'+ ele.collectChannelApplicateTypeId +'">'+ ele.channelName +'</option>');
        //         });
        //         form.render('select');
        //     });
        // });
    });

    //搜索设备信息
    $(".search_btn").on("click",function(){
        var equipmentId = $("#equipment-list").val();
        var dateCoure = $("#date-coure").val();
        if(equipmentId == ''){
            layer.msg("请选择搜索设备");
            return;
        }

    });

    //初始化统计图，循环遍历出当前设备下所有统计的数据
    $(".search_btn").click(function () {
        //获取选择查询的范围
        var coure = $("#date-coure").val();
        var curdate = new Date(1546355252000);//测试一下1537519202000
        var endSolrDate = getSolrDate(curdate);//开始时间
        var enddate = new Date(curdate.getTime() - 24*60*60*1000);
        if (coure == 0) {
            enddate = new Date(curdate.getTime() - 24*60*60*1000);
        } else if(coure == 1) {
            enddate = new Date(curdate.getTime() - 7*24*60*60*1000);
        } else if(coure == 2) {
            enddate = new Date(curdate.getTime() - 30*24*60*60*1000);
        }

        var startSolrDate = getSolrDate(enddate);//结束时间
        var equipmentId = $("#equipment-list").val();
        if(equipmentId == ''){
            layer.msg("请选择搜索设备");
            return;
        }
        // var checkItemId = $("#checkItem").val();
        // var colTime = $("#col-time").val();

        if(equipmentId == ''){
            layer.msg("请选择搜索设备");
            return;
        }
        var searchObj = {};
        searchObj.page = 0;
        searchObj.limit = 20000;//设置默认最大查询范围
        searchObj.equipmentId = equipmentId;
        // searchObj.checkItemId = checkItemId;
        searchObj.downAcquisitionTime = startSolrDate;
        searchObj.upAcquisitionTime = endSolrDate;
        //开启加载动画
        window.myindex = layer.load(2);
        $.get("/search/datarecord/page/query?",searchObj,function (data) {
            //当前设备的检测项目
            var checkItemArr = [];
            if (data.data.length <= 0) {
                //关闭加载动画
                layer.close(myindex);
                layer.msg("没有找到数据！换一个时间范围试试？");
            }
            $.each(data.data,function (i, ele) {
                if (contains(checkItemArr,ele.checkItemId) != -1 && ele.checkItemName != "设备信息") {
                    checkItemArr.unshift(ele.checkItemId);
                }
            });
            $("#echart-content").html("");
            for (var i = 0;i < checkItemArr.length;i++) {
                //x轴时间组件
                var xAxisdataArr = [];
                var seriesArr = [];
                var checkMessage = {};
                $.each(data.data,function (j, ele) {
                    if (checkItemArr[i] == ele.checkItemId) {
                        var date = new Date(ele.acquisitionTime);
                        var dateStr = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
                        xAxisdataArr.unshift(dateStr);
                        seriesArr.unshift(ele.processedData);
                        checkMessage.title = ele.checkItemName + "趋势";
                        checkMessage.legendData = ele.checkItemName;
                        checkMessage.seriesName = ele.checkItemName;
                        checkMessage.yAxisformatter = ele.unit;

                    }
                });
                //初始化统计图
                initChart(i,xAxisdataArr,seriesArr,checkMessage);
            }
        });
    });

    /**
     * 初始化统计图
     * @param index
     * @param xAxisdataArr
     * @param seriesArr
     * @param checkMessage
     */
    function initChart(index,xAxisdataArr, seriesArr,checkMessage) {
        //关闭加载动画
        layer.close(myindex);
        var innerHtml = '<div class="layui-elem-quote layui-quote-nm magb0 echart-box">' +
            '                <div id="line-chart-'+ index +'" style="margin-top:10px;width: 95%; height: 400px;">' +
            '                </div>' +
            '            </div>';
        $("#echart-content").append(innerHtml);
        //折线图
        var lineChart = echarts.init(document.getElementById('line-chart-' + index));
        var option = {
            title: {
                text: checkMessage.title,
                subtext: ' '
            },
            tooltip: {
                trigger: 'axis'
            },
            legend: {
                data:[checkMessage.legendData]
            },
            toolbox: {
                show: true,
                feature: {
                    dataZoom: {
                        yAxisIndex: 'none'
                    },
                    dataView: {readOnly: false},
                    magicType: {type: ['line', 'bar']},
                    restore: {},
                    saveAsImage: {}
                }
            },
            xAxis:  {
                type: 'category',
                boundaryGap: false,
                data: xAxisdataArr
            },
            yAxis: {
                type: 'value',
                axisLabel: {
                    formatter: '{value} ' + checkMessage.yAxisformatter
                }
            },
            series: [
                {
                    name:checkMessage.seriesName,
                    type:'line',
                    data:seriesArr,
                    markPoint: {
                        data: [
                            {type: 'max', name: '最大值'},
                            {type: 'min', name: '最小值'}
                        ]
                    },
                    markLine: {
                        data: [
                            {type: 'average', name: '平均值'}
                        ]
                    }
                }
            ]
        };
        lineChart.setOption(option);
    }

    /**
     * 获取当前时间，以solr中date的格式 2018-08-27T02:28:58Z
     * @param date
     * @returns {string}
     */
    function getSolrDate(date) {
        var year = date.getFullYear();
        var month = (date.getMonth() + 1) >= 10 ? (date.getMonth() + 1) : "0" + (date.getMonth() + 1);
        var day = date.getDate() >= 10 ? date.getDate() : "0" + date.getDate();
        var hour = date.getHours() >= 10 ? date.getHours() : "0" + date.getHours();
        var minutes = date.getMinutes() >= 10 ? date.getMinutes() : "0" + date.getMinutes();
        var seconds = date.getSeconds() >= 10 ? date.getSeconds() : "0" + date.getSeconds();
        var dateStr = year + '-' + month + '-' + day + 'T' + hour + ':' + minutes + ':' + seconds + 'Z';
        return dateStr;
    }

    /**
     * 判断数组中是否存在元素
     * @param arr
     * @param obj
     * @returns {number}
     */
    function contains(arr, obj) {
        if (arr.length != 0) {
            for (var i = 0;i < arr.length;i++) {
                if(arr[i] == obj) {
                    return -1;
                }
            }
        }
        return 0;
    }

});